/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.scrumpmt.web;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import javax.ejb.EJB;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.primefaces.event.DateSelectEvent;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.ScheduleEntrySelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
import org.scrumpmt.domain.Reunion;
import org.scrumpmt.domain.Sprint;
import org.scrumpmt.ejb.SprintFacade;
import org.scrumpmt.ejb.TipoReunionFacade;

@ManagedBean
@ViewScoped
public class ScheduleController extends BasicBean implements Serializable {

    private ScheduleModel eventModel;
    private ScheduleModel lazyEventModel;
    private ScheduleEvent event = new DefaultScheduleEvent();
    private SprintFacade sprintFacade = lookupSprintFacade();
    @EJB
    private TipoReunionFacade tipoReunionFacade;
    
    FacesContext context = FacesContext.getCurrentInstance();
    ProductoSeleccionadoBean productoBean = (ProductoSeleccionadoBean) context.getApplication().
            evaluateExpressionGet(context, "#{productoSeleccionadoBean}", ProductoSeleccionadoBean.class);

    public ScheduleController() {
        eventModel = new DefaultScheduleModel();

        String sprintId = productoBean.getSprintActual();

        Sprint sprint = sprintFacade.findById(sprintId);
        Collection<Reunion> reuniones = sprint.getReunionCollection();

        eventModel.addEvent(new DefaultScheduleEvent(sprint.getDes(), sprint.getFecini(), sprint.
                getFecfin(), true));
        for (Iterator<Reunion> it = reuniones.iterator(); it.hasNext();) {
            Reunion reunion = it.next();
            eventModel.addEvent(new DefaultScheduleEvent(reunion.getIdTipreunion().getDes(), reunion.
                    getFec(), reunion.getFec()));
        }

        lazyEventModel = new LazyScheduleModel() {

            @Override
            public void loadEvents(Date start, Date end) {
                clear();

                Date random = getRandomDate(start);
                addEvent(new DefaultScheduleEvent("Lazy Event 1", random, random));

                random = getRandomDate(start);
                addEvent(new DefaultScheduleEvent("Lazy Event 2", random, random));
            }
        };
    }

    public Date getRandomDate(Date base) {
        Calendar date = Calendar.getInstance();
        date.setTime(base);
        date.add(Calendar.DATE, ((int) (Math.random() * 30)) + 1);        //set random day of month

        return date.getTime();
    }

    public Date getInitialDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar.getTime();
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    public ScheduleModel getLazyEventModel() {
        return lazyEventModel;
    }

    public ScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }

    public void addEvent(ActionEvent actionEvent) {
        String msg;
        Long id_ttarea;
        if (event.getId() == null) {
            if (event.getTitle().equals("2")) {
                msg = "Sprint Planning Meeting";
                id_ttarea = new Long(event.getTitle());
            } else if (event.getTitle().equals("3")) {
                msg = "Sprint Review Meeting";
                id_ttarea = new Long(event.getTitle());
            } else if (event.getTitle().equals("4")) {
                msg = "Sprint Retrospective";
                id_ttarea = new Long(event.getTitle());
            } else {
                msg = "Daily Scrum";
                id_ttarea = new Long("1");
            }

            eventModel.addEvent(new DefaultScheduleEvent(msg, event.getStartDate(), event.getEndDate()));
            log.log(Level.INFO, "Estoy insertando una reunion: {0}", event.getTitle());
            Reunion reu = new Reunion();
            reu.setFec(event.getStartDate());
            reu.setIdTipreunion(tipoReunionFacade.find(id_ttarea));

            Sprint sp = sprintFacade.find(new Long(productoBean.getSprintActual()));
            sp.getReunionCollection().add(reu);
            reu.setIdSprintFk(sp);
            
            sprintFacade.edit(sp);
            log.log(Level.INFO, "Reunion insertada: {0}", reu.getIdTipreunion().getDes());
        } else {
            eventModel.updateEvent(event);
            log.log(Level.INFO, "Estoy actualizando una reunion: {0}", event.getTitle());
        }

        event = new DefaultScheduleEvent();
    }

    public void onEventSelect(ScheduleEntrySelectEvent selectEvent) {
        event = selectEvent.getScheduleEvent();
    }

    public void onDateSelect(DateSelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", selectEvent.getDate(), selectEvent.getDate());
    }

    public void onEventMove(ScheduleEntryMoveEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.
                getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

        addMessage(message);
    }

    public void onEventResize(ScheduleEntryResizeEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.
                getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

        addMessage(message);
    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    private SprintFacade lookupSprintFacade() {
        try {
            Context c = new InitialContext();
            return (SprintFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/SprintFacade!org.scrumpmt.ejb.SprintFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
